package repository

import entity.Activity
import entity.User
import org.hibernate.criterion.Restrictions

// Chase
class UserRepositoryImpl : UserRepository {
    override fun findByWxOpenId(wxOpenId: String): User? {
        return null
    }

    // test: ok 21.5.7
    // modified: 21.5.8 chase
    override fun findByPhoneNumber(phoneNumber: String): User? {
        return executeTransaction {
            val criteria = it.createCriteria(User::class.java)
            criteria.add(Restrictions.eq("phoneNumber", phoneNumber))
            criteria.uniqueResult() as User?

            // val ql = criteria.list()
            // if (ql.size > 0) {
            //     ql[0] as User
            // } else null
        }
    }

    // test: ok 21.5.7
    // modified: 21.5.8 chase
    override fun findByPublishedActivities(activity: Activity): User {
        return executeTransaction {
            val criteria = it.createCriteria(User::class.java)
            // That means activity.publisher must exist.
//            criteria.add(Restrictions.eq("id", activity.publisher.id))
            criteria.add(Restrictions.idEq(activity.publisher.id))
            criteria.uniqueResult() as User

            // val ql = criteria.list()
            // if (ql.size > 0) {
            //     ql[0] as User
            // } else User().also { it.userName = "no-result" }
        }
    }

    // test: ok 21.5.7
    // modified: 21.5.8 chase
    override fun findByExaminedActivities(activity: Activity): User {
        return executeTransaction {
            val criteria = it.createCriteria(User::class.java)
            // That means activity.publisher must exist.
            // criteria.add(Restrictions.eq("id", activity.examiner.id))
            criteria.add(Restrictions.idEq(activity.examiner.id))
            criteria.uniqueResult() as User

            // val ql = criteria.list()
            // if (ql.size > 0) {
            //     ql[0] as User
            // } else User().also { it.userName = "no-result" }
        }
    }
}